import { Component, OnInit, Injector, Output, EventEmitter, Input } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import { tokenName } from '@angular/compiler';
import { ActivatedRoute, Params } from '@angular/router';
import { internal } from '../../internal.data';
import { copyStyles } from '@angular/animations/browser/src/util';

declare var $: any;
@Component({
  selector: 'app-automatic-matching',
  templateUrl: './automatic-matching.component.html',
  styleUrls: ['./automatic-matching.component.css']
})
export class AutomaticMatchingComponent implements OnInit {

  total: number = 0;
  pageNo: number = 1;
  pageSize: number = 20;
  queryCriteria:any = '';
  naturalNum: number = 0;
  @Input() internalParam: any;
  @Input() internalIndexedTheme:any;
  isSelectAll: boolean = false;
  isChose: boolean = false;
  tabValList: Array<object>;
  @Input() searchData: any;
  iitArr = [];
  themeTableName: any;
  getCheckedThemeId = [];

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit() {
  }

  /**
   * 查询已标引的主题词列表
   */
  _getInexingAutoList() {
    this.getCheckedThemeId = [];
    this.iitArr = [];
    if (this.internalParam) {
      //已标引的主题词
      this._reorganizeIndexedKeywords();

      this.themeTableName = this.internalParam.themeTableName;
      let url = this.server.baseUrl + 'Service/IdxProduct/getInexingAutoList';
      let data = {
        "token": internal.retrieval.token,
        "productId": this.internalParam['productId'],
        "themeTableId": this.internalParam['themeTableId'],
        "pageNo": this.pageNo,
        "pageSize": this.pageSize,
        "queryCriteria": this.queryCriteria
      };
      this.request.postRequest(url, data).then((res: any) => {

        if (res.result_code === '0000') {
          this.tabValList = res.result;
          this.total = res.length;
          this.naturalNum = internal.pagination.naturalNum;
        } else {
          this.hintsService.messages(res.message, res.result_code);
        }

        this._cancelChecked();
        return;
      })
        .catch((err: any) => {
          this._cancelChecked();
          return;
        });
    }

  }

  //重组已标引的主题词
  _reorganizeIndexedKeywords(){
    if(this.internalIndexedTheme && this.internalIndexedTheme.length > 0){
      for (let item of this.internalIndexedTheme) {
        let themeWordsId = item.idxProductsThemeVo.idxThemeWords.themeWordsId;
        if(themeWordsId != ''){
          this.iitArr[themeWordsId] = true;
        }
      }
    }
  }

  _deleteId(id:any){
    this.removeTableService.getRemoveTableId = [];
    this.removeTableService.keywordRemoveChose(true, id, 1)['bool'];
  }

  //删除
  _delete(){

    let url = this.server.baseUrl + 'Service/IdxProduct/delInexingAuto';
    this.removeTableService
    .confirmRemove('ids',url,'token',internal.retrieval.token)
    .then(res => {
      if(res.result_code == '0000'){
        this._getInexingAutoList();
      }
      this.hintsService.messages(res.message,res.result_code);
      return;
    })
    .catch(err => {
      this.hintsService.messages('error','error');
      return;
    });
  }

  //搜索
  search() {
    this.queryCriteria = this.searchData;
    this._getInexingAutoList();
  }
  //响应搜索
  changesearch() {
      this.search();
  }

  /**
   * 确定标引
   */
  _addAutomaticMatchingTheme() {
    if (this.getCheckedThemeId.length > 0) {
      this.server.onSubmitAppViewEmit.emit(this.getCheckedThemeId);
    }
  }

  _emptyAutomaticMatching(){
    this.getCheckedThemeId = [];
  }

  /**
   * 全选
   * @param bool
   * @param tabVal
   */
  _selectAll(bool, tabVal) {
    this.isChose = this.isSelectAll = bool;
    if(bool && tabVal) {
  		this.getCheckedThemeId = [];
  		tabVal.forEach((obj, i, object)=>{
        let arr = {
          'txt':  obj['themeWordsName'],
          'val':  obj['themeWordsId']
        };
        this.getCheckedThemeId.push(arr);
      });
  	}
  	else {
  		this.getCheckedThemeId = [];
  	}
  }

  /**
  * 选中的主题词
  * @param event 
  * @param id 
  */
  _nodeSelect(bool, event) {
    if (bool == true) {
        let arr = {
          'txt': event.themeWordsName,
          'val': event.themeWordsId
        };
        this.getCheckedThemeId.push(arr);

    } else {
      this.getCheckedThemeId.splice(this.getCheckedThemeId.findIndex(item => item['val'] === event.id), 1);
    }
    
  }

  /**
   * 重置表格复选框、选中的ID
   */
  private _cancelChecked() {
    this.isChose = this.isSelectAll = false;
    this.removeTableService._clearId("id");
  }

  /**
   * 判断是否为空数组
   */
  _isEmpty() {
    if (this.getCheckedThemeId.length == 0) {
      return true;
    }
    return false;
  }

  /**
   * 分页
   * @param pagination 
   */ 
  _pagination(pagination: Array<any>) {
    this.pageNo = pagination[0].pageNumber;
    this.pageSize   = pagination[0].pageSize;
    this.naturalNum = (this.pageNo - 1) * this.pageSize;
    this._getInexingAutoList();
  }

}
